package org.example.demo7.web;

import java.io.*;
import java.util.List;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
@WebServlet("/VerifyServlet")
public class VerifyCaptchaServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userInput = request.getParameter("userInput");
        String userName = request.getParameter("userName");
        String correctCaptcha = (String) request.getSession().getAttribute("captcha");
        // 判断用户输入和验证码是否都不为空
        if (userInput != null && correctCaptcha != null && userInput.equalsIgnoreCase(correctCaptcha)) {
            // 获取 ChatServlet 实例
            ChatServlet chatServlet = (ChatServlet) getServletContext().getAttribute("ChatServlet");
            if (chatServlet == null) {
                // 初始化一个新的 ChatServlet 实例
                chatServlet = new ChatServlet();
                chatServlet.init(getServletConfig());
                getServletContext().setAttribute("ChatServlet", chatServlet);
            }
            // 获取在线用户列表
            List<String> onlineUsers = chatServlet.getOnlineUsers();
            // 添加用户到在线用户列表
            if (!onlineUsers.contains(userName)) {
                chatServlet.addOnlineUser(userName);
            }
                request.getSession().setAttribute("userName", userName);
                response.sendRedirect("chatRoom.jsp?userName=" + userName);
            }
            else {
            // 验证失败，返回登录页面并显示错误信息
            request.setAttribute("result", "验证码错误，请重新输入！");
            request.getRequestDispatcher("index.jsp").forward(request, response);
        }

    }
}